﻿using Quartz;
using Quartz.Impl;
using Quartz.Impl.Matchers;
using System.Threading.Tasks;

namespace Anay.TaskScheduling.Common
{
    public class QuartzHelper
    {
        public const string SCHEDULERNAME = "AnayScheduler";
        /// <summary>
        /// 调度器
        /// </summary>

        IScheduler scheduler = null;
        /// <summary>
        /// 调度工厂
        /// </summary>
        ISchedulerFactory schedulerFactory = null;
        public QuartzHelper()
        {

            schedulerFactory = new StdSchedulerFactory();
            scheduler = GetSchedulerAsync().GetAwaiter().GetResult();
        }

        /// <summary>
        /// 获取调度器
        /// </summary>
        /// <returns></returns>
        private async Task<IScheduler> GetSchedulerAsync()
        {
            if (scheduler == null)
            {

                return await schedulerFactory.GetScheduler();
            }

            return scheduler;
        }

        //检查调度器各个方法

        /// <summary>
        /// 调度器开始
        /// </summary>
        public void Start()
        {
            scheduler.Start();

        }

        /// <summary>
        /// 调度器是否启动
        /// </summary>
        /// <returns></returns>
        public bool IsStarted()
        {
            return scheduler.IsStarted;
        }

        /// <summary>
        /// 停止调度器
        /// </summary>
        public void Shutdown()
        {

            scheduler.Shutdown();
        }
        /// <summary>
        /// 调度器是否停止
        /// </summary>
        /// <returns></returns>
        public bool IsShutdown()
        {

            return scheduler.IsShutdown;
        }


        /// <summary>
        /// 暂停所有job
        /// </summary>
        public void PauseAll()
        {

            scheduler.PauseAll();
        }

        /// <summary>
        /// 重启所有Job
        /// </summary>
        public void ResumeAll()
        {
            scheduler.ResumeAll();
        }



        public void DeleteJobs()
        {
            var JobKeys = scheduler.GetJobKeys(GroupMatcher<JobKey>.AnyGroup());
            scheduler.DeleteJobs(JobKeys.Result);
        }

        /// <summary>
        /// 默认几秒钟就执行一次
        /// </summary>
        /// <returns></returns>J
        public async Task SimpleTriggerRunAsync(IJob job, JobConfig.Ep_task_config jobConfig)
        {
            try
            {
                IJobDetail jobDetail = JobBuilder.Create(job.GetType())
                                                 .UsingJobData("ConfigId", jobConfig.Id)
                                                 .WithIdentity(new JobKey(jobConfig.JobName + "_Job", jobConfig.JobName + "_Group")).Build();
                ITrigger trigger = TriggerBuilder.Create()
                                                 .WithIdentity(new TriggerKey(jobConfig.JobName + "_trigger", jobConfig.JobName + "_Group"))
                                                 .StartNow()
                                                 .WithSimpleSchedule(x => x
                                                    .WithIntervalInSeconds(int.Parse(jobConfig.TimeExpression))
                                                     .RepeatForever())
                                                 .Build();
                await scheduler.ScheduleJob(jobDetail, trigger);
            }
            catch (System.Exception ex)
            {
                Anay.Logging.LogHelper.Write("外部调度器出错（创建单一triggerjob）：" + ex.Message + "\r\n" + ex.StackTrace);
            }
        }

        /// <summary>
        /// cron表达式执行
        /// </summary>
        /// <returns></returns>
        public async Task CronTriggerRun(IJob job, JobConfig.Ep_task_config jobConfig)
        {
            try
            {
                IJobDetail jobDetail = JobBuilder.Create(job.GetType())
                                                  .UsingJobData("ConfigId", jobConfig.Id)
                                                  .WithIdentity(new JobKey(jobConfig.JobName + "_Job", jobConfig.JobName + "_Group")).Build();
                ICronTrigger trigger = (ICronTrigger)TriggerBuilder.Create()
                            .WithIdentity(new TriggerKey(jobConfig.JobName + "_trigger", jobConfig.JobName + "_Group"))
                            .WithCronSchedule(jobConfig.TimeExpression)
                             .Build();
                await scheduler.ScheduleJob(jobDetail, trigger);
            }
            catch (System.Exception ex)
            {
                Anay.Logging.LogHelper.Write("外部调度器出错（创建cron表达式job）：" + ex.Message + "\r\n" + ex.StackTrace);
            }
        }
    }
}
